<template>
  <div class="departments">
    <el-card class="mycard">
      <el-tabs>
        <el-tab-pane label="组织结构"></el-tab-pane>
      </el-tabs>

      <div class="box">
        <treetools @openPanel="openPanel" :item="topitem" istop="true"></treetools>
        <hr />

        <!-- 树形结构 -->
        <el-tree class="mytree" :data="list" default-expand-all>
          <treetools
            @editPanel="editPanel"
            @openPanel="openPanel"
            @updatedata="getDepartment"
            slot-scope="{ data }"
            :item="data"
          ></treetools>
        </el-tree>
      </div>
    </el-card>
    <!-- 对话框 -->
    <addpanel
      ref="addpanel"
      :showDialog.sync="showDialog"
      @updatedata="getDepartment"
      :currentItem="currentItem"
    ></addpanel>
  </div>
</template>

<script>
import { getDepartmentsApi } from '@/api/departments.js'
export default {
  name: 'departments',
  components: {
    treetools: () => import('./components/treetools.vue'),
    addpanel: () => import('./components/addpanel.vue')
  },
  data () {
    return {
      list: [],
      topitem: {
        label: '江苏传智播客教育科技股份有限公司'
      },
      showDialog: false,
      currentItem: {}
    }
  },
  methods: {
    // 获取所有组织架构数据
    async getDepartment () {
      const res = await getDepartmentsApi()
      // console.log(res);
      this.list = this.trunData(res.data.depts, '')

      this.topitem = { ...res.data.depts[0], manager: '负责人' }
    },
    // 转换data数据
    trunData (arr, pid) {
      var newArr = []
      arr.forEach(item => {
        if (item.pid === pid) {
          var children = this.trunData(arr, item.id)
          if (children.length > 0) {
            item.children = children
          }
          newArr.push(item)
        }
      })
      return newArr
    },
    // 控制子组件显示与隐藏
    openPanel (item) {
      this.showDialog = true
      this.currentItem = item
    },
    // 编辑面板
    editPanel (item) {
      this.showDialog = true
      this.currentItem = item
      // 调用子组件方法
      this.$refs.addpanel.getDeptsById(item.id)
    }
  },
  created () {
    this.getDepartment()
  }
}
</script>

<style lang="scss" scoped>
.departments {
  margin: 20px;

  .mycard {
    padding: 20px;

    .box {
      width: 90%;
      margin: 50px auto;
    }

    .mytree {
      margin-top: 20px;
    }

    ::v-deep.el-tree-node__content {
      height: 40px;
    }
  }
}
</style>
